package com.bittech.chatroom.web.api;

import com.bittech.chatroom.entity.UserAccount;
import com.bittech.chatroom.service.UserAccountService;
import com.bittech.chatroom.web.view.BaseViewServlet;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: yuisama
 * @Date: 2019-06-25 16:59
 * @Description:
 */
@WebServlet(urlPatterns = "/doLogin")
public class UserLoginHandlerServlet extends BaseViewServlet {
    private UserAccountService userAccountService = new UserAccountService();
    private Map<String,String> map = new ConcurrentHashMap<>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        UserAccount account = userAccountService.userLogin(userName,password);
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter out = resp.getWriter();
        // 登录校验失败，重定向登录界面
        if (account == null) {
            out.print("<script type=\"text/javascript\">alert('用户名或密码错误，请重试！');" +
                    "window.location.href=\"/index\";" +
                    "</script>");
        }else {
            // 跳转到聊天界面
            Template template = getTemplate("/chat.ftl",req,resp);
            map.put("username",userName);
            try {
                template.process(map,out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
